# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2018/6/18 10:03
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : decorator.py
# @Software   : PyCharm
# -----------------------------------------
from utils.log import log
from utils.mysql import Mysql


# 记录接口api请求日志
def record_api_log(func):
    def swapper(*args, **kwargs):
        infos = func(*args, **kwargs)
        if infos.get("status"):
            log.info(infos)
        else:
            log.error(infos)
        return infos

    return swapper


def check_conn(func):
    infos = {
        "status": False,
        "msg": '',
        "type": None
    }

    def swapper(*args, **kwargs):
        """
        : args: src dest database
        """
        src=args[0]
        dest=args[1]
        dbsrc = Mysql(src)
        if not dbsrc.check_connect(src.get("database")):
            infos["msg"] = f"could not connect db: {src} {src.get('database')}"
            infos["type"] = "src"
            return infos

        dbdest = Mysql(dest)
        if not dbdest.check_connect(dest.get("database")):
            infos["msg"] = f"could not connect db: {dest} {dest.get('database')}"
            infos["type"] = "dest"
            return infos

        return func(*args, **kwargs)

    return swapper


def check_table_key(func):
    infos = {
        "status": False,
        "msg": '',
        "type": None
    }

    def swapper(*args,**kwargs):
        """
        : args: src dest database
        """
        src=args[0]
        dest=args[1]
        if "table" not in src:
            infos["msg"] = "src: not found table key"
            return infos

        if "table" not in dest:
            infos["msg"] = "dest: not found table key"
            return infos

        return func(*args,**kwargs)

    return swapper


def check_src_dest(func):
    infos = {
        "status": False,
        "msg": ''
    }

    def swapper(*args, **kwargs):
        """
        : args: src dest
        """
        src = args[0]
        dest = args[1]
        if src["host"] == dest["host"] and src["port"] == dest["port"] and src["database"] == dest["database"]:
            infos["msg"] = "could not compare at the same dbinstance database"
            return infos
        return func(*args, **kwargs)

    return swapper
